import string, cgi, datetime, sqlite3, json, time
from os import curdir, sep, listdir
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class RequestHandler(BaseHTTPRequestHandler):
    
    def do_GET(self):
        try:
            # multiple file handler
            if self.path == '/' or self.path.endswith('.html') or self.path.endswith('.js') or self.path.endswith('.css') or self.path.endswith('.png') or self.path.endswith('.gif'):
                self.send_response(200)
                
                if self.path == '/' or self.path.endswith('.html'): self.send_header('Content-type','text/html')
                elif self.path.endswith('.js'): self.send_header('Content-type','text/javascript')
                elif self.path.endswith('.css'): self.send_header('Content-type','text/css')
                elif self.path.endswith('.png'): self.send_header('Content-type','image/png')
                elif self.path.endswith('.gif'): self.send_header('Content-type','image/gif')
                
                self.end_headers()
                
                f = open (curdir + sep + self.path if self.path != '/' else 'index.html', 'rb')
                self.wfile.write(f.read())
                f.close()
            
            # dynamic json content
            elif self.path.endswith('.json'):
                self.send_response(200)
                self.send_header('Content-type','application/json')
                self.end_headers()
                
                conn = sqlite3.connect(curdir + sep + 'raceclock.sqlite')
                
                # latest.json
                if self.path.endswith('latest.json'):
                    c = conn.cursor()
                    now = datetime.datetime.now()
                    c.execute('SELECT event_id, event_title, event_datetime FROM events WHERE event_datetime > %s ORDER BY event_datetime ASC LIMIT 1' % (time.mktime(now.timetuple())))
                    row = c.fetchone()
                    
                    if row == None:
                        self.wfile.write(json.dumps({'result':False}))
                    else:
                        self.wfile.write(json.dumps({
                            'result':True,
                            'id':row[0],
                            'title':row[1],
                            'datetime':row[2]
                        }))
                        
                    c.close()
                
                # sponsors.json
                elif self.path.endswith('sponsors.json'):
                    result = []
                    images = listdir(curdir + sep + 'rotate_images')
                    for image in images:
                        if image.endswith('.png'): result.append(image)
                    self.wfile.write(json.dumps(result))
                
                conn.close()
                
            # dynamic pages
            elif self.path.endswith('.manager'):
                conn = sqlite3.connect(curdir + sep + 'raceclock.sqlite')
                
                self.send_response(200)
                self.send_header('Content-type','text/html')
                self.end_headers()
                
                # events list
                if self.path.endswith('events.manager'):
                    content = ''
                    c = conn.cursor()
                    
                    f = open (curdir + sep + 'raceclock-manager-add.tpl')
                    add = f.read()
                    f.close()
                    
                    f = open (curdir + sep + 'raceclock-manager.tpl')
                    tpl = f.read()
                    f.close()
                    
                    content += add                    
                    content += '<table id="events">'
                    content += '<tr><th>ID</th><th>Description</th><th>Date &amp; Time</th><th>Options</th></tr>'
                    c.execute('SELECT event_id, event_title, event_datetime FROM events ORDER BY event_datetime ASC')
                    for row in c:
                        timestamp = datetime.datetime.fromtimestamp(row[2])
                        content += '<tr><td>%s</td><td>%s</td><td>%s</td><td><a href="javascript:editEvent(%s);">Edit</a> | <a href="javascript:deleteEvent(%s);">Delete</a></td></tr>' % (row[0], row[1], timestamp, row[0], row[0])
                    content += '</table>'
                    
                    tpl = tpl.replace('{{ content }}', content)
                    
                    c.close()
                    
                    self.wfile.write(tpl)
                    
                conn.close();
            
        except IOError:
            self.send_error(404, 'File Not Found')
    
    def do_POST(self):
        conn = sqlite3.connect(curdir + sep + 'raceclock.sqlite')
        
        ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
        if ctype == 'multipart/form-data':
            postvars = cgi.parse_multipart(self.rfile, pdict)
        elif ctype == 'application/x-www-form-urlencoded':
            length = int(self.headers.getheader('content-length'))
            postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)
        else:
            postvars = {}
        
        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()
        
        # Delete an event
        if self.path.endswith('delete.json'):
            id = int(postvars.get('id', [0])[0])
            c = conn.cursor()
            c.execute('DELETE FROM events WHERE event_id=?', (id,))
            conn.commit()
            c.close()
            self.wfile.write(json.dumps({'result':True}))
        
        # Add an event
        elif self.path.endswith('add.json'):
            description = postvars.get('description', [''])[0]
            dt = postvars.get('datetime', [''])[0]
            
            epoch = int(time.mktime(time.strptime(dt, '%Y-%m-%d %H:%M:%S')))
            values = [description, epoch]
            
            c = conn.cursor()
            c.execute('INSERT INTO events(event_title, event_datetime) VALUES (?,?)', values)
            conn.commit()
            c.close()
            self.wfile.write(json.dumps({'result':True}))
        
        # Modify event
        elif self.path.endswith('modify.json'):
            description = postvars.get('description', [''])[0]
            dt = postvars.get('datetime', [''])[0]
            id = int(postvars.get('id',[0])[0])
            
            epoch = int(time.mktime(time.strptime(dt, '%Y-%m-%d %H:%M:%S')))
            values = [description, epoch, id]
            
            c = conn.cursor()
            c.execute('UPDATE events SET event_title = ?, event_datetime = ? WHERE event_id = ?', values)
            conn.commit()
            c.close()
            self.wfile.write(json.dumps({'result':True}))
        
        conn.close()
    
def main():
    try:
        server = HTTPServer(('localhost', 8888), RequestHandler)
        print 'Race Clock has started .... http://localhost:8888'
        server.serve_forever()
    except KeyboardInterrupt:
        print 'Race Clock shutting down'
        server.socket.close()
        
        
if __name__ == '__main__':
    main()